<?php
/**
 * @version	$Id: request.php 25 2011-02-11 00:04:45Z gregdaynes@gmail.com $
 * @package	jEvolve.SyncrClient
 * @copyright  Copyright (C) 2010 jEvolve, LLC. All rights reserved.
 * @license	GNU General Public License
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport('joomla.application.component.model');

class SyncrModelRequest extends JModel
{
	var $_log = null;
	
	function __construct() {
		parent::__construct();
		
		// new class
		$evl = new evolveLibrary;
		
		// load some evl stuff
		$this->_log = $evl->loadHelper('log');
		$this->_htmlparser = $evl->loadHelper('htmlparser');
	}
	
	public function getData()
	{
		
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			if (!$this->_buildQuery()) {
				$this->_log->simpleLog('request.php/getData: Could not find content item', 'syncr');
				
				JError::raiseNotice(204, JText::_('Could not find content item'));
			}
						
			if (!$this->_preProcess()) {
				$this->_log->simpleLog('request.php/getData: could not pre process item', 'syncr');
			}
									
			echo json_encode($this->_data);		
		}
		
		return;
	}
	
	private function _buildQuery()
	{
		$db =& JFactory::getDBO();
	
		$this->_itemId = JRequest::getInt('itemId', 0);
		
		$query = 'SELECT title'
			   .', alias'
			   .', introtext'
			   .', `fulltext`'
			   .', state'
			   .', sectionid'
			   .', catid'
			   .', created'
			   .', created_by'
			   .', created_by_alias'
			   .', modified'
			   .', modified_by'
			   .', publish_up'
			   .', publish_down'
			   .', attribs'
			   .', version'
			   .', metakey'
			   .', metadesc'
			   .', access'
			   .', metadata'
			   .' FROM #__content'
			   .' WHERE id = '.$this->_itemId
			   ;
		$db->setQuery($query);
			
		if ($this->_data = $db->loadObject()) {
			return true;
		}
		
		return false;
	}
	
	private function _preProcess()
	{		
		$html[] = $this->_htmlparser->str_get_html($this->_data->introtext);
		$html[] = $this->_htmlparser->str_get_html($this->_data->fulltext);
		
		$relative_images = null;
		foreach($html as $html) {
			foreach($html->find('img') as $element) {				
				if (strpos($element->src, 'http://') === false) {
					$relative_images[] = $element->src;
				}
			}
		}
		
		if ($relative_images === null) {
			$this->_log->simpleLog('request.php/_preProcess: no images to process', 'syncr');
			return;
		}
		
		foreach($relative_images as $i=>$image_path) {
			//$relative_images[$i]['absolute'] = JURI::base().ltrim($image_path['relative'], "/");
			
			$this->_data->introtext = str_replace($image_path, JURI::base().ltrim($image_path, "/"), $this->_data->introtext);
			$this->_data->fulltext = str_replace($image_path, JURI::base().ltrim($image_path, "/"), $this->_data->fulltext);
		}
		
		return;
	}
}